package com.terren.spider.core.html.scheme.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.transaction.TransactionStatus;

import com.terren.spider.core.html.configuration.Configuration;
import com.terren.spider.db.service.TiebaUserService;
import com.terren.spider.entity.biz.TiebaUser;
import com.terren.spider.util.common.CommonUtil;

public class TiebaUserScheme extends BasicCustomScheme{
	private TiebaUserService tiebaUserService;
	private List<TiebaUser> users;
	
	@Override
	public Set<String> findTargetUrl(Configuration configuration) {
		tiebaUserService = CommonUtil.getBean(TiebaUserService.class);
		TransactionStatus tran = null;//开启事务
		Set<String> urlSet=new HashSet<>();
		try {
			tran = tiebaUserService.startTransaction();//开启事务
			
			users=tiebaUserService.getTiebaUserDetailList();
			if (CollectionUtils.isNotEmpty(users)) {
				tiebaUserService.updateProgressStatus(users);// set  status = 9
				tiebaUserService.commitTransaction(tran);//提交事务
				for (int i = 0; i < users.size(); i++) {
					urlSet.add(users.get(i).getUrl());
				}
			}
			
				
		} catch (Exception e) {
			log.error("TiebaUserScheme findTargetUrl error",e);
		} finally {
			if (tran!=null&&!tran.isCompleted()) {
				tiebaUserService.commitTransaction(tran);//提交事务
			}
		}
		return urlSet;
	}
	@Override
	public void postFetch(Configuration configuration) {
		if (CollectionUtils.isNotEmpty(users)) {
			try {
				tiebaUserService.updateDoneStatus(users);
				tiebaUserService.updateFetchtimes(users);
			} catch (Exception e) {
				log.error("TiebaUserScheme postFetch error",e);
			}
		}
	}

}
